package com.ys.peony.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yklab.library.refreshlayout.adapters.NewCommonRecyclerViewAdapter;
import com.yklab.library.refreshlayout.holder.CommonRecyclerViewHolder;
import com.yklab.library.refreshlayout.inter.OnClickCommonListener;
import com.yklab.library.ui.adapter.LoadMoreWrapper;
import com.ys.peony.R;
import com.ys.peony.app.BaseApplication;
import com.ys.peony.app.HttpURL;
import com.ys.peony.app.YSConstant;
import com.ys.peony.base.BaseActivity;
import com.ys.peony.enums.BusinessDetailStatus;
import com.ys.peony.enums.SwipeDirect;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespBean;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.model.AppointModel;
import com.ys.peony.model.AppointResp;
import com.ys.peony.model.DaimianshenModel;
import com.ys.peony.model.DaimianshenResp;
import com.ys.peony.model.UserModel;
import com.ys.peony.ui.adapter.AppointListAdapter;
import com.ys.peony.ui.view.DialogContract;
import com.ys.peony.ui.view.zlistview.enums.DragEdge;
import com.ys.peony.ui.view.zlistview.enums.ShowMode;
import com.ys.peony.ui.view.zlistview.widget.ZListView;
import com.ys.peony.ui.view.zlistview.widget.ZSwipeItem;
import com.ys.peony.ui.widget.Divider;
import com.ys.peony.utils.JSONUtil;
import com.ys.peony.utils.LoadingProgressUtils;
import com.ys.peony.utils.LogUtil;
import com.ys.peony.utils.NetUtils;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * 预约列表
 * Created by yml on 17/5/12.
 */

public class AppointListActivity extends ListActivity<AppointModel> implements OnClickCommonListener {
    //请求code
    public static final int REQUEST_CODE = 1000;
    private View actionbar;
    private TextView addBtn;

    @Override
    protected int getContentResId() {
        return super.getContentResId();
    }

    @Override
    protected void initView() {
        setShowToolbar(false);
        super.initView();
        initWidget();
        initAdapter();
        //数据请求
        refreshlayout.beginRefreshing();
    }

    private void initWidget() {
        actionbar = LayoutInflater.from(this).inflate(R.layout.activity_appointlist, null);
        view_actionbar.setVisibility(View.GONE);
        view_toolbar.setVisibility(View.GONE);
        rootview.addView(actionbar, 0);
        addBtn = actionbar.findViewById(R.id.add_btn);
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent it = new Intent(AppointListActivity.this, AddAppointActivity.class);
                it.putExtra("addFlag", true);
                startActivityForResult(it, YSConstant.ACTIVITY_ADD_YW_CLIENT);
            }
        });
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        mAdapter = new NewCommonRecyclerViewAdapter<AppointModel>(this, mList, R.layout.appoint_item_layout) {
            @Override
            public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
                super.onBindViewHolder(holder, position);
                final AppointModel model = mList.get(position);
                if (model == null) {
                    return;
                }
                ((CommonRecyclerViewHolder) holder).setText(R.id.yuyue_name_tv, BaseApplication.getInstance().getResources().getString(R.string.name_lable) + model.getName())
                        .setText(R.id.yuyue_phone_tv, BaseApplication.getInstance().getResources().getString(R.string.phone_lable) + model.getPhone())
                        .setText(R.id.yuyue_car_style_tv, BaseApplication.getInstance().getResources().getString(R.string.jiekuanren_car) + model.getBrand_name())
                        .setText(R.id.yuyue_carnum_tv, BaseApplication.getInstance().getResources().getString(R.string.jiekuanren_carnum) + model.getPlate_number())
                        .setText(R.id.yuyue_identification_tv, BaseApplication.getInstance().getResources().getString(R.string.identification_lable) + model.getId_card());
                final ZSwipeItem swipeItem = ((CommonRecyclerViewHolder) holder).getView(R.id.swipe_item);
                final TextView delete = ((CommonRecyclerViewHolder) holder).getView(R.id.item_delete_tv);
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        delAppointItem(model.getId(), holder.getAdapterPosition());
                        swipeItem.close();
                    }
                });
            }
        };
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mAdapter.setOnClickListener(this);
        mLoadMoreWrapper = new LoadMoreWrapper(mAdapter);
        recyclerview.setHasFixedSize(true);
        recyclerview.addItemDecoration(new Divider(this));
        recyclerview.setLayoutManager(mLayoutManager);
        recyclerview.setAdapter(mLoadMoreWrapper);
    }

    /**
     * 删除预约登记
     *
     * @param busiAppointmentId
     */
    public void delAppointItem(long busiAppointmentId, final int position) {
        if (!NetUtils.isNetworkConnected(this)) {
            ToastUtils.showToast(this, getResources().getString(R.string.no_net_error));
            return;
        }
        LoadingProgressUtils.showProgressDialog(this);
        JCHttpManagerUtils httpManager = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<>();
        params.put("userId", Long.parseLong(SharePreferencesUtils.getInstance().getUserModel().getId()));
        params.put("busiAppointmentId", busiAppointmentId);

        httpManager.get(HttpURL.deleteBusiAppointment, params, new BaseRespCallBack() {

            @Override
            public void onRespSuccess(String respStr) {
                mLoadMoreWrapper.notifyItemRemoved(position);
                mList.remove(position);
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                ToastUtils.showToast(msg);
            }
        });
    }

    @Override
    protected void getData() {
        UserModel userModel = SharePreferencesUtils.getInstance().getUserModel();
        if (null == userModel) {
            ToastUtils.showToast("用户信息为空");
            return;
        }
        if (!NetUtils.isNetworkConnected(this)) {
            ToastUtils.showToast(getResources().getString(R.string.no_net_error));
            return;
        }
        final JCHttpManagerUtils httpManagerUtils = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<>();
        params.put("userId", Long.parseLong(userModel.getId()));
        params.put("currentPage", curPageNum);
        params.put("pageNum", YSConstant.PAGE_NUM);
        httpManagerUtils.get(getUrl(), params, new BaseRespCallBack() {
            @Override
            public void onRespSuccess(String respStr) {
                refreshlayout.endRefreshing();
                setData(respStr);
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                refreshlayout.endRefreshing();
                showBlankView();
            }
        });
    }

    @Override
    protected String getUrl() {
        return HttpURL.busiAppointmentPage;
    }

    private void setData(final String data) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                AppointResp resp = JSONUtil.parseObject(data, AppointResp.class);
                if (actionType == YSConstant.ACTION_TYPE_DOWN && (resp == null || resp.getDataList() == null || resp.getDataList().size() < 1)) {
                    showBlankView();
                    return;
                }
                List<AppointModel> list = resp.getDataList();
                if ((list == null || list.size() < 1) && actionType == YSConstant.ACTION_TYPE_UP) {
                    mLoadMoreWrapper.setLoadState(LoadMoreWrapper.LOADING_END);
                    return;
                }
                if (actionType == YSConstant.ACTION_TYPE_DOWN) {
                    hideBlankView();
                    mList.clear();
                    mList.addAll(list);
                    mLoadMoreWrapper.notifyDataSetChanged();
                } else if (actionType == YSConstant.ACTION_TYPE_UP) {
                    mList.addAll(list);
                    mRequestList.addAll(list);
                    mLoadMoreWrapper.notifyItemRangeInserted(mList.size() - list.size() + 1, list.size());
                }
            }
        });
    }

    @Override
    public void onClickListener(View view, int position) {
        //图片编辑
        Intent it = new Intent(AppointListActivity.this, AddAppointActivity.class);
        it.putExtra("addFlag", false);
        it.putExtra("appointModel", mList.get(position));
        startActivityForResult(it, YSConstant.ACTIVITY_ADD_YW_CLIENT);
    }

    @Override
    public void observerSearchText(List list, String text) {
    }

    @Override
    protected void searchData(String respStr) {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (YSConstant.ACTIVITY_ADD_YW_CLIENT == requestCode && RESULT_OK == resultCode) {
            refreshlayout.beginRefreshing();
        }
    }

}
